package Campus.help.user.service.impl;

import Campus.help.common.config.MyThreadLocal;
import Campus.help.common.exception.payException;
import Campus.help.common.utils.R;
import Campus.help.user.dao.UserCountMapper;
import Campus.help.user.entity.UserCount;
import Campus.help.user.service.UserCountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
public class UserCountServiceImpl extends ServiceImpl<UserCountMapper, UserCount> implements UserCountService {

    @Autowired
    private UserCountMapper userCountMapper;

    @Resource
    private MyThreadLocal threadLocal;

    @Override
    public R addMoney(BigDecimal amount) {
        Long id = threadLocal.get().getId();
        boolean f = userCountMapper.addMoney(id,amount);
        if (f)
            return R.ok();
        return R.error();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R payForMoney(BigDecimal amount) throws payException {
        Long id = threadLocal.get().getId();
        boolean f = userCountMapper.payForMoney(id,amount);
        if (f) {
            boolean b = userCountMapper.addMoney(1L, amount);
            if (!b)
                throw new payException("支付失败");
            return R.ok();
        }
        return R.error();
    }

    @Override
    public R returnMoney(BigDecimal amount,Long id) throws payException {
        boolean f = userCountMapper.returnMoney(1L,amount);
        if (f) {
            boolean b = userCountMapper.addMoney(id, amount);
            if (!b)
                throw new payException("退款失败");
            return R.ok();
        }
        return R.error();
    }

    @Override
    @Transactional
    public R complete(Long userId, BigDecimal amount) {
        userCountMapper.complete(userId,amount);
        userCountMapper.returnMoney(1L,amount);
        return R.ok();
    }

    @Override
    public int initCount(long userId) {
        UserCount userCount = new UserCount();
        userCount.setUserId(userId);
        int insert = userCountMapper.insert(userCount);
        return insert;
    }

    @Override
    public R getMoney() {
        Long id = threadLocal.get().getId();
        BigDecimal f = userCountMapper.getMoney(id);
        if (f!=null)
            return R.ok().put("money",f.doubleValue());
        return R.error();
    }
}
